<template>
    <div>
        <div ref='myPage' style='width: 100%; height:calc(100vh - 100px);'>
            <SeeksRelationGraph
                ref='seeksRelationGraph'
                :options='graphOptions'
                :on-node-click='onNodeClick'
                :on-line-click='onLineClick'
            >
                <div slot='node' slot-scope='{node}'>
                    <div @contextmenu.prevent.stop='showNodeMenus(node, $event)'>
                        <span style='font-size: 15px; padding: 10px 0'>{{ node.text }}</span>
                    </div>
                </div>
            </SeeksRelationGraph>
        </div>

        <div
            v-show='isShowNodeMenu'
            :style="{left: nodeMenu.x + 'px', top: nodeMenu.y + 'px'}"
            style='z-index: 999; padding: 10px; background-color: #fff; border: #eee solid 1px; box-shadow: 0px 0px 8px #ccc; position: absolute'
        >
            <div class='menu-item' @click.stop='doAction()'>设置准则节点</div>
        </div>
        <!--  弹窗  -->
        <el-dialog
            title='添加准则'
            :close-on-click-modal='false'
            append-to-body
            :visible.sync='dialogVisible'
            @close='cloneDialog'
            width='30%'
        >
            <!-- 内容 -->
            <el-tree
                :data='treeData'
                show-checkbox
                default-expand-all
                node-key='id'
                ref='tree'
                highlight-current
                :props="{ label: 'text',children: 'children'}">
            </el-tree>
            <!-- 按钮 -->
            <span slot='footer' class='dialog-footer'>
          <el-button @click='dialogVisible = false'>取 消</el-button>
          <el-button type='primary' @click='handleSubmit'>确 定</el-button>
        </span>
        </el-dialog>
    </div>
</template>

<script>
import SeeksRelationGraph from 'relation-graph';
import { tranListToTreeData } from '@/utils';

export default {
    name: 'Demo',
    components: { SeeksRelationGraph },
    props: {
        jmData: {
            type: Object, default: () => {
            }
        },
        schemeLinks: {},
        rootId: {}
    },
    data() {
        return {
            dialogVisible: false,
            isShowNodeMenu: false,
            currentNode: {},
            nodeMenu: { x: 0, y: 0 },
            treeData: [],
            nodes: [],
            links: [],
            prj: [],
            currentCase: '横向树状图谱',
            isShowCodePanel: false,
            graphOptions: {
                'backgrounImageNoRepeat': false,
                'defaultLineWidth': 2, // 线条宽度
                'defaultNodeShape': 1,
                'defaultNodeBorderWidth': 0,
                'defaultLineShape': '',
                'defaultLineColor': '#67c23a',
                'layouts': [
                    {
                        'label': '中心',
                        'layoutName': 'tree',
                        'layoutClassName': 'seeks-layout-center',
                        'defaultJunctionPoint': 'border',
                        'defaultNodeShape': 0,
                        'defaultLineShape': 1
                        // "levelDistance": ""

                    }
                ],
                'defaultLineMarker': {
                    'markerWidth': 12,
                    'markerHeight': 12,
                    'refX': 6,
                    'refY': 6
                    // "data": "M2,2 L10,6 L2,10 L6,6 L2,2" // 箭头形状
                }

            }
        };
    },
    created() {
        console.log(this.jmData);
        let obj = { ...this.jmData };
        this.nodes = this.handleTreeData([obj]);
        this.handleLinks(this.nodes);
        // if (this.schemeLinks && this.schemeLinks.length > 0) {
        //   this.handleProject(this.schemeLinks)
        // }

    },
    mounted() {
        console.log(document.body);
        // document.body.ondrop = function (event) {
        //     console.log(event);
        //     event.preventDefault();
        //     event.stopPropagation();
        // }
        this.showSeeksGraph();
    },
    methods: {
        // 处理树形数据
        handleTreeData(data, res = []) {
            data.forEach(item => {
                res.push({ ...item });
                if (item.children && item.children.length > 0) {
                    this.handleTreeData(item.children, res);
                }
            });
            return res;
        },
        // 建立节点连接
        handleLinks(arr) {
            console.log(arr);
            let schemeArr = this.schemeLinks.map(item => item.id.toString());
            let nodes = [];
            arr.forEach(item => {
                delete item.children;
                if (schemeArr && !schemeArr.includes(item.id)) {
                    if (item.id !== this.rootId) {
                        console.log({ 'from': item.xh.toString(), 'to': item.id.toString() });
                        this.links.push({ 'from': item.xh.toString(), 'to': item.id.toString() });
                    }
                    // arr.forEach(sub => {
                    //     if (item.id == sub.xh) {
                    //         console.log(item.id, sub.xh);
                    //         this.links.push({ 'from': item.id.toString(), 'to': sub.id.toString() });
                    //     }
                    // });
                } else {
                    console.log(item);
                    item.color = '#43a2f1';
                    if (item.keys && item.keys.length > 0) {
                        arr.forEach(sub => {
                            if (item.keys.includes(sub.id.toString()) && sub.id != this.rootId) {
                                this.links.push({
                                    'from': sub.id.toString(),
                                    'to': item.id.toString(),
                                    'color': 'red'
                                });
                            }
                        });
                    }

                }
            });
        },
        // 建立方案连接 arr: 方案数组
        handleProject(arr) {
            // arr.forEach(sub => {
            //     sub.color = '#43a2f1';
            //     this.nodes.forEach(item => {
            //         // console.log()
            //         if (sub.pid.toString().includes(item.id.toString()) && item.id != this.rootId) {
            //             this.links.push({ 'from': item.id.toString(), 'to': sub.id.toString(), 'color': 'red' });
            //         }
            //     });
            // });
        },
        // 显示关系图
        showSeeksGraph(query) {
            var __graph_json_data = {
                'rootId': this.rootId,
                'nodes': this.nodes,
                'links': this.links
            };
            this.$refs.seeksRelationGraph.setJsonData(__graph_json_data, (seeksRGGraph) => {
                // 这些写上当图谱初始化完成后需要执行的代码
                document.addEventListener('click', this.closeRightMenu);
            });
        },
        showNodeMenus(nodeObj, $event) {
            console.log(nodeObj, $event);
            let schemeArr = this.schemeLinks.map(item => item.id.toString());
            if (!schemeArr.includes(nodeObj.id)) return false;
            this.currentNode = nodeObj;
            var _base_position = this.$refs.myPage.getBoundingClientRect();
            this.isShowNodeMenu = true;
            this.nodeMenu.x = $event.clientX - 200;
            this.nodeMenu.y = $event.clientY - _base_position.y;
        },
        // 点击菜单时事件
        doAction() {
            let treeKeys = this.schemeLinks.map(item => item.keys)[0];

            console.log(treeKeys);
            let arr = this.nodes.filter(item => !item.color);
            this.treeData = tranListToTreeData(JSON.parse(JSON.stringify(arr)), 'id', 'xh');
            this.dialogVisible = true;
            this.isShowNodeMenu = false;
            if (!treeKeys) return false
            this.$nextTick(() => {
                this.$refs.tree.setCheckedKeys(treeKeys, true);
            });


        },
        closeRightMenu() {
            this.isShowNodeMenu = false;
        },
        handleSubmit() {
            // 获取选中的节点
            let treeKeys = this.$refs.tree.getCheckedKeys(true);
            if (treeKeys.length < 1) return this.$message.warning('请选择节点！');
            this.dialogVisible = false;
            this.$emit('sx', this.currentNode.id, treeKeys);

        },
        onNodeClick(nodeObject, $event) {
            this.isShowNodeMenu = false;
            console.log('onNodeClick:', nodeObject);
        },
        onLineClick(lineObject, $event) {
            console.log('onLineClick:', lineObject);
        },
        cloneDialog() {
            this.treeData = [];
            console.log(this.treeData);
        }
    }
};
</script>

<style scoped>
.menu-item {
    line-height: 30px;
    padding-left: 10px;
    cursor: pointer;
    color: #444;
    font-size: 15px;
}

.menu-item:hover {
    color: red;
}
</style>
